package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.PointDefend;
import com.example.entity.authority.*;
import com.example.mapp.*;
import com.example.service.PartyContractService;
import com.example.util.PromotionUtil;
import com.example.util.ResultUtil;
import com.example.util.StringUtil;
import com.example.util.SystemPointUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by youkun on 2018/3/18.
 */
@Service
public class PartyContractServiceImpl implements PartyContractService{

    private final static Logger logger = (Logger) LoggerFactory.getLogger(PartyContractServiceImpl.class);

    @Autowired
    private PartyContractMapp partyContractMapp;

    @Autowired
    private PartyContractFileMapp partyContractFileMapp;

    @Autowired
    private PartyByFileMapp partyByFileMapp;

    @Autowired
    private PromotionMapp promotionMapp;

    @Autowired
    private PartyMapp partyMapp;

    @Autowired
    private PointFlowMapp pointFlowMapp;

    @Autowired
    private PartyContractProjectMapp partyContractProjectMapp;

    @Autowired
    private ElevatorMapp elevatorMapp;
    @Override
    @Transactional
    public Map<String, Object> add(PartyContract partyContract) {
        try {
            //添加合同基本信息
            if (StringUtil.isNotBlank(partyContract.getFileList())) {
                if (partyContract.getFileList().contains(",")) {
                    List<String> asList = Arrays.asList(partyContract.getFileList().split(","));
                    String join = StringUtil.join(asList, ",");
                    partyContract.setFileList(join);
                }
            }
           partyContractMapp.insert(partyContract);
           //添加合同的附件
			Party party = partyMapp.queryById(partyContract.getPartyId() + "");
			if ("1".equals(party.getPartyType())) {
				party.setPartyType("1");
			} else if ("2".equals(party.getPartyType())) {
				party.setPartyType("2");
			}
			PromotionUtil.calcParty(promotionMapp, 20, party.getPartyType(), partyContract.getPartyId(), "添加1份合同", "0");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }finally {
            // 判断是否是电梯责任险合同   两种不同情况，进行分别处理
            if ("电梯责任险合同".equals(partyContract.getContractType()) && partyContract.getRoleId() == 16 ) {
                // 获取缓存
                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                PointDefend defend = infoCache.getKeyByValue("insure_elevator_insurance");

                // 获取当前用户，计算积分
                Map<String, Object> maps = pointFlowMapp.findUserInfo(partyContract.getPartyId());
                long mark = (long) maps.get("mark");
                int round = (int) (mark + defend.getMark());

                // 更新用户信息总积分
                String userId = maps.get("userId").toString();
                int i1 = pointFlowMapp.updateMark(round, userId);

                String userName = maps.get("userName").toString();
                String partyName = maps.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "新增电梯责任险加单位积分");

                // 添加电梯安全管理员的积分
                PointDefend defendUser = infoCache.getKeyByValue("insure_elevator_insurance_user");
                Map<String, Object> usermaps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(partyContract.getLoggerUserId()));
                long usermark = (long) usermaps.get("mark");
                int userround = (int) (usermark + defendUser.getMark());

                // 更新电梯安全管理员的积分
                String usersId = maps.get("userId").toString();
                int i2 = pointFlowMapp.updateMark(round, usersId);
                SystemPointUtil.insertFlow(pointFlowMapp, i2, defendUser, userround, maps.get("userName").toString(), maps.get("partyName").toString(), "新增电梯责任险加安全员积分");

            }
            // 判断当前用户是否是使用单位并维保委托合同
            if("维保委托合同".equals(partyContract.getContractType()) && partyContract.getRoleId() == 16){
                // 先计算使用单位的积分
                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                PointDefend defend = infoCache.getKeyByValue("sign_contract_daily_maintenance");

                Map<String, Object> maps = pointFlowMapp.findUserInfo(partyContract.getPartyId());
                long mark = (long) maps.get("mark");
                int round = (int) (mark + defend.getMark());

                // 更新用户信息总积分
                String userId = maps.get("userId").toString();
                int i1 = pointFlowMapp.updateMark(round, userId);

                String userName = maps.get("userName").toString();
                String partyName = maps.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "新增维保委托合同");

                // 添加电梯安全管理员的积分
                PointDefend defendUser = infoCache.getKeyByValue("sign_contract_daily_maintenance_user");
                Map<String, Object> usermaps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(partyContract.getLoggerUserId()));
                long usermark = (long) usermaps.get("mark");
                int userround = (int) (usermark + defendUser.getMark());

                // 更新电梯安全管理员的积分
                String usersId = maps.get("userId").toString();
                int ii = pointFlowMapp.updateMark(round, usersId);
                SystemPointUtil.insertFlow(pointFlowMapp, ii, defendUser, userround, maps.get("userName").toString(), maps.get("partyName").toString(), "新增电梯责任险加安全员积分");


                // 获取维保单位Id
                String secondParty = partyContract.getSecondParty();
                Map<String, Object> userPartyMaps = pointFlowMapp.findUserInfo(Long.valueOf(secondParty));
                PointDefend pointDefend = infoCache.getKeyByValue("use_unit_bear_maintenance");
                long userMark = (long) userPartyMaps.get("mark");
                int userRound = (int) (userMark + (pointDefend.getMark() * partyContract.getContractNumber()));

                // 更新维保单位主体信息总积分
                String userUserId = maps.get("userId").toString();
                int i2 = pointFlowMapp.updateMark(userRound, userUserId);

                String userUserName = userPartyMaps.get("userName").toString();
                String userPartyName = userPartyMaps.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i2, pointDefend, userRound, userUserName, userPartyName, "承担电梯维保工作");



            }
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> queryByPartyIdList(PartyContract partyContract) {
        List<PartyContract> partyContractList = null;
        Map<String,Object> map = new HashMap<String,Object>();
        try{

            PartyContract contract = new PartyContract();
            contract.setPageSize(partyContract.getPageSize());
            contract.setCurrentPage(partyContract.getCurrentPage());
            contract.setPartyType(partyContract.getPartyType());

            // 初步判断系统管理人员以及管理人员
            if(partyContract.getPartyType()==1){
                contract.setFirstPartyName(partyContract.getFirstPartyName());
                // 维保人员
                contract.setSecondParty(String.valueOf(partyContract.getPartyId()));
                partyContract = contract;
            }
            //使用人员
            if(partyContract.getPartyType() ==2){
                contract.setSecondPartyName(partyContract.getSecondPartyName());
                // 系统管理员以及管理人员
                contract.setFirstParty(String.valueOf(partyContract.getPartyId()));
                partyContract = contract;
            }
            Page<PartyContract> page = null;
            if(partyContract.getCurrentPage() != null && partyContract.getPageSize() != null){
                page = PageHelper.startPage(partyContract.getCurrentPage(),partyContract.getPageSize());
            }
            partyContractList = partyContractMapp.queryByPartyIdList(partyContract);

            map.put("list",partyContractList);
            if(page != null){
                map.put("total",page.getTotal());
            }
            map.put("dataTime",new Date());
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败",null);
        }
        return  ResultUtil.returnSuccess("成功",map);
    }

    @Override
    @Transactional
    public Map<String, Object> deleteById(String id) {
        try {
            // 通过Id判断是否是电梯责任险合同
            PartyContract partyContract = partyContractMapp.queryById(id);
//            if ("电梯责任险合同".equals(partyContract.getContractType())) {
//                // 判断合同是否过期
//                Date date1 = DateUtils.parseDate(partyContract.getEndTime(), "yyyyMMdd");
//                Date date2 = DateUtils.parseDate(DateUtils.formatDate(new Date(), "yyyyMMdd"), "yyyyMMdd");
//                if (date1.compareTo(date2) > 0) {
//                    // 获取缓存
//                    PointDefendInfoCache infoCache = new PointDefendInfoCache();
//                    PointDefend defend = infoCache.getKeyByValue("insure_elevator_insurance");
//
//                    // 获取当前用户，计算积分
//                    Map<String, Object> maps = pointFlowMapp.findUserInfo(partyContract.getPartyId());
//                    long mark = (long) maps.get("mark");
//                    int round = (int) (mark - defend.getMark());
//
//                    // 更新用户信息总积分
//                    String userId = maps.get("userId").toString();
//                    int i1 = pointFlowMapp.updateMark(round, userId);
//
//                    String userName = maps.get("userName").toString();
//                    String partyName = maps.get("partyName").toString();
//                    SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "删除电梯责任险");
//                }
//            }
            //删除合同
            partyContractMapp.deleteById(id);
            //删除合同附件
            List<PartyByFile> list = partyByFileMapp.findByPartyId(id);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    partyContractFileMapp.deleteByContractId(list.get(i).getId().toString());
                }
            }
            //删除附件的关联
            partyByFileMapp.deleteByPartyId(id);

            //删除合同下项目
            List<PartyContractProject> projects = partyContractProjectMapp.queryByContractId(id);
            if( ! CollectionUtils.isEmpty(projects)){
                for (int i = 0,len = projects.size(); i < len; i++) {
                    partyContractProjectMapp.delete(projects.get(i).getId().toString());
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(), null);
        }
        return ResultUtil.returnSuccess("成功", null);
    }

    @Override
    public Map<String, Object> queryByPartyIdFile(String id) {
        List<PartyContractFile> list = new ArrayList<PartyContractFile>();
        try{
            list = partyContractFileMapp.queryByPartyId(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return  ResultUtil.returnSuccess("成功",list);
    }

    /**
     * 修改合同列表
     * @param partyContract
     * @return
     */
    @Override
    public Map<String, Object> updateContract(PartyContract partyContract) {
        List<PartyContractFile> list = new ArrayList<PartyContractFile>();
        try{
            //修改合同照片
            if (StringUtil.isNotBlank(partyContract.getFileList())) {
                if (partyContract.getFileList().contains(",")) {
                    List<String> asList = Arrays.asList(partyContract.getFileList().split(","));
                    String join = StringUtil.join(asList, ",");
                    partyContract.setFileList(join);
                }
            }
            partyContractMapp.updateContract(partyContract);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return  ResultUtil.returnSuccess("成功",list);
    }

    /**
     * 添加合同项目
     * @param partyContractProject
     * @return
     */
    @Override
    public Map<String, Object> addProject(PartyContractProject partyContractProject) {

        try{
            partyContractProjectMapp.insert(partyContractProject);

            /**
             * 获取新添加项目关联的电梯台账，更新台账中的项目名称
             */
            this.updateProgrom(partyContractProject);
            /**
             * 获取合同所有项目，更新合同电梯数量
             */
            int contractNumber = 0;
            List<PartyContractProject> projects =  partyContractProjectMapp.queryByContractId(partyContractProject.getContractId());
            if( ! CollectionUtils.isEmpty(projects)){
                for(PartyContractProject project : projects){
                    contractNumber+= project.getElevatorCount();
                }
            }
            PartyContract partyContract = new PartyContract();
            partyContract.setId(Long.parseLong(partyContractProject.getContractId()));
            partyContract.setContractNumber(contractNumber);
            partyContractMapp.updateContractNumber(partyContract);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> queryProjectByContractId(PartyContractProject partyContractProject) {
        List<PartyContractProject> partyContractProjects = null;
        Map<String,Object> map = new HashMap<>();
        try{
            Page<PartyContractProject> page = null;
            if(partyContractProject.getCurrentPage() != null && partyContractProject.getPageSize() != null){
                page = PageHelper.startPage(partyContractProject.getCurrentPage(),partyContractProject.getPageSize());
            }
            partyContractProjects = partyContractProjectMapp.queryByContractId(partyContractProject.getContractId());

            map.put("list",partyContractProjects);
            if(page != null){
                map.put("total",page.getTotal());
            }
            map.put("dataTime",new Date());
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    @Override
    public Map<String, Object> deleteProject(Map<String, Object> map) {
        try{
            List<String> ids = (List<String>) map.get("ids");
            if(CollectionUtils.isEmpty(ids)){
                logger.warn("需要删除的项目标识为传入。。");
                return ResultUtil.returnError("",null);
            }
            for(String id : ids){
                partyContractProjectMapp.delete(id);
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",map);
    }

    @Override
    public Map<String, Object> updateProject(PartyContractProject partyContractProject) {

        try{
           partyContractProjectMapp.updateProject(partyContractProject);

            /**
             * 获取新添加项目关联的电梯台账，更新台账中的项目名称
             */
            this.updateProgrom(partyContractProject);


            /**
             * 获取合同所有项目，更新合同电梯数量
             */
            int contractNumber = 0;
            List<PartyContractProject> projects =  partyContractProjectMapp.queryByContractId(partyContractProject.getContractId());
            if( ! CollectionUtils.isEmpty(projects)){
                for(PartyContractProject project : projects){
                    contractNumber+= project.getElevatorCount();
                }
            }
            PartyContract partyContract = new PartyContract();
            partyContract.setId(Long.parseLong(partyContractProject.getContractId()));
            partyContract.setContractNumber(contractNumber);
            partyContractMapp.updateContract(partyContract);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    /**
     * 更新电梯台账里的项目名称
     * @param partyContractProject
     */
    public void updateProgrom(PartyContractProject partyContractProject) {
        if (StringUtils.isNotBlank(partyContractProject.getElevatorIds())) {
            Map map = new HashMap();
            map.put("elevatorIds", partyContractProject.getElevatorIds());
            map.put("programName", partyContractProject.getProjectName());
            elevatorMapp.updateProjectName(map);
        }
    }


}
